package com.shihb.esjddemo.service;


import com.alibaba.fastjson.JSON;
import com.shihb.esjddemo.pojo.Content;
import com.shihb.esjddemo.util.EsConst;
import com.shihb.esjddemo.util.HtmlParseUtil;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.text.Text;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * Description: Version:1.0.0
 *
 * @author shihb
 * @date 2020/4/17 23:10
 */
@Service
public class JdGoodsService {

  @Autowired
  private RestHighLevelClient restHighLevelClient;

  /**
   * 解析数据，放入索引中
   */
  public Boolean parserContent(String keyWord) throws Exception {
    List<Content> contents = new HtmlParseUtil().parseJd(keyWord);
// 创建请求
    BulkRequest bulkRequest = new BulkRequest();
    bulkRequest.timeout("60s");
    // 批处理请求
    for (int i = 0; i < contents.size(); i++) {
      bulkRequest.add(
          new IndexRequest(EsConst.ES_INDEX)
              .source(JSON.toJSONString(contents.get(i)), XContentType.JSON)
      );
    }
    //客户端发送请求,获取响应结果
    BulkResponse res = restHighLevelClient.bulk(bulkRequest, RequestOptions.DEFAULT);
    //是否失败
    return !res.hasFailures();
  }

  /**
   * 获取数据
   */
  public List<Object> searchContent(String keyWord, int pageNum, int pageSize) throws IOException {
    if (pageNum < 1) {
      pageNum = 1;
    }

    //条件搜索
    SearchRequest searchRequest = new SearchRequest(EsConst.ES_INDEX);
    SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
    searchSourceBuilder
        // 高亮设置 要高亮的字段，不用匹配多个高亮，高亮标签
        .highlighter(new HighlightBuilder().field("title").requireFieldMatch(true)
            .preTags("<span style=\"color: red\">").postTags("</span>"))
        // 查询条件
        .query(QueryBuilders.termQuery("title", keyWord))
        // 超时时间
        .timeout(new TimeValue(60, TimeUnit.SECONDS))
        //分页
        .from(pageNum)
        .size(pageSize);
    searchRequest.source(searchSourceBuilder);
    SearchResponse res = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);

    List<Object> list = new ArrayList<>();
    // 解析结果
    for (SearchHit hit : res.getHits().getHits()) {
//      获取高亮字段
      HighlightField title = hit.getHighlightFields().get("title");
      StringBuilder newTitle = new StringBuilder();
      if (title != null) {
        // 拼接高亮字符串
        for (Text text : title.fragments()) {
          newTitle.append(text);
        }
      }
      // 获取结果,没有高亮
      Map<String, Object> sourceAsMap = hit.getSourceAsMap();
      // 替换高亮的字符串
      sourceAsMap.put("title", newTitle.toString());
      list.add(sourceAsMap);

    }
    return list;

  }

}
